"""
实现一个日志输出类，该类功能如下:
1.能被其他类实例化
2.留有日志输出接口，其他类调用该接口时打印日志，并自带时间格式
3.程序关闭时所有其他类打印的日志必须全部按程序执行顺序保存到本地文件名为"log.txt"

待定------------------------------------------------------------------
"""

import os
import logging
import time


class ToolLog(object):
    _instance = None

    def __init__(self):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        self.ch = logging.StreamHandler()
        self.fh = None
        self.formatter = logging.Formatter('%(message)s')

        self.ch.setFormatter(self.formatter)
        self.logger.addHandler(self.ch)

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls)
        return cls._instance

    def setfh(self, logPath):
        if self.fh is None:
            logfie = os.path.join(logPath, "运行日志.log")
            self.fh = logging.FileHandler(logfie)
            self.fh.setFormatter(self.formatter)
            self.logger.addHandler(self.fh)

    def printLog(self, logStr, error=False, raiseException=False):
        content = "[{0}]{1}".format(time.strftime("%Y-%m-%d %H:%M:%S"), logStr)
        if error is True:
            logType = "Error"
        else:
            logType = "Log"
        content = "[{0}]{1}".format(logType, content)
        if raiseException:
            raise Exception(content)
        else:
            self.logger.info(content)
